<template>
	<view>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="仓库名称">
							<uni-easyinput v-model="searchModel.name" placeholder="请输入仓库名称" />
						</uni-forms-item>
						<uni-forms-item label="状态">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.status" :localdata="warehouseStatusList" />
							</view>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							form-type="reset"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
		</up-popup>
		<view class="content">
			<!--内容-->
			<view class="table">
				<ty-table-tree
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:tree-props="{ children: 'children' }"
					:expand-row-keys="expandRowKeys"
					@expand-change="onExpandChange"
					defaultExpandAll
					stripe
					border>
					<template v-slot:info="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">名称：<text class="table-td-text">{{row.name}}</text></view>
							<view class="table-td-row">编码：<text class="table-td-text">{{row.code}}</text></view>
							<view class="table-td-row">地址：<text class="table-td-text">{{row.addr}}</text></view>
							<view class="table-td-row">类型：<text class="table-td-text">{{arrText(warehouseTypeList, row.type)}}</text></view>
						</view>
					</template>
					<template v-slot:user="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">用户：<text class="table-td-text">{{row.userName}}</text></view>
							<view class="table-td-row">联系：<text class="table-td-text">{{row.phone}}</text></view>
						</view>
					</template>
					<template v-slot:status="{ row }">
						<view class="table-td-cell">
							<uni-tag size="small" :type="row.status === 0 ? 'success' : ''" :text="arrText(warehouseStatusList, row.status)" />
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table-tree>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue'
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { warehouse } from "@/api/erp_api/warehouse"
import { warehouseType } from "@/api/system/dict/data"
import { isObjectEmptySimple, copyText, arrText } from '@/utils/ty.js';
import useUserStore from '@/store/modules/user'
import { warehouseStatusList } from '@/utils/config.js'

	const userStore = useUserStore()
	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
	})
	
	// 获取仓库类型
	const warehouseTypeList = ref([])
	const getWarehouseType = () => {
		return warehouseType().then(res => {
			warehouseTypeList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		name: '',
		status: ''
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			name: '',
			status: ''
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '', type: 'expand', width: '40px' },
		{ title: '仓库信息', key: 'info' },
		{ title: '联系方式', key: 'user', width: '200rpx' },
		{ title: '状态', key: 'status', width: '100rpx' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.name) {
			params.name = searchModel.value.name
		}
		if (searchModel.value.status || searchModel.value.status === 0) {
			params.status = searchModel.value.status
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		warehouse(params).then(res => {
			tableList.value = buildTree(res.rows) || []
			expandRowKeys.value = tableList.value.filter(item => item.isChildren).map(item => item.id)
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	// 数据处理
	const buildTree = (arr) => {
		const idSet = new Set(arr.map(item => item.id))
		  
		// 找出所有可能的根节点（无父节点或父节点不存在）
		const roots = arr.filter(item => 
			!item.parentId || !idSet.has(item.parentId)
		);
	
		const result = []
		const visited = new Set()
	
		function traverse(node) {
			if (visited.has(node.id)) return
			visited.add(node.id)
			result.push(node)
			
			// 查找所有直接子节点
			arr.filter(child => child.parentId === node.id)
				 .forEach(child => traverse(child))
		}
		roots.forEach(root => traverse(root))
		return result.map(item => {
			return {
				...item,
				isChildren: arr.filter(child => child.parentId === item.id).length > 0,
				isShow: true
			}
		})
	}
	
	// 查询所有子集
	function findAllChildren(nodes, parentId) {
	  const ids = []
		const queue = [parentId]
		
		while (queue.length) {
			const currentId = queue.shift()
			nodes.filter(node => node.parentId === currentId)
					 .forEach(child => {
						 ids.push(child.id)
						 queue.push(child.id)
					 });
		}
		return ids
	}
	
	// 默认展开项
	let expandRowKeys = ref([])
	const onExpandChange = (e) => {
		const expandedKeys = e.expandedKeys
		const ids = findAllChildren(tableList.value, e.key)
		expandData(ids, expandedKeys, expandedKeys.indexOf(e.key) > -1)
	}
	const expandData = (ids, expandedKeys, show) => {
		tableList.value = tableList.value.map(item => {
			if (ids.indexOf(item.id) > -1) {
				item.isShow = show ? expandedKeys.indexOf(item.parentId) > -1 ? show : false : show
			}
			return item
		})
	}
	
	// 点击行
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/warehouse/warehouseDetail?id=${row.id}`
		})
	}
	
	onMounted(async () => {
		await getWarehouseType()
		searchFirst()
	})
</script>

<style scoped>
.form {
	background-color: #fff;
}
</style>
